import React, { useState, useEffect } from "react";
import { DotLoading } from "antd-mobile";
import img from "./1.jpeg";

const waitList: any = []; //等待队列
let isRender: boolean = false; //控制渲染条件

const waitRender = () => {
  const res = waitList.shift();
  if (!res) return;
  setTimeout(() => {
    res();
  }, 300);
};
/*
分片渲染：简单的说就是一个执行完再执行下一个，其思想是建立一个队列，通过定时器来进行渲染，比如说一共有3次，先把这三个放入到数组中，当第一个执行完成后，并剔除执行完成的，在执行第二个，直到全部执行完毕，渲染队列清空。
*/
const HOC = (Component: any) => (props: any) => {
  const [show, setShow] = useState<boolean>(false);
  useEffect(() => {
    waitList.push(() => {
      setShow(true);
    });
    if (!isRender) {
      waitRender();
      isRender = true;
    }
  }, []);
  return show ? (
    <Component waitRender={waitRender} {...props} />
  ) : (
    <div style={{ margin: 25 }}>
      <DotLoading color="primary" />
      加载中
    </div>
  );
};

const Child: React.FC<{ name: string; waitRender: () => void }> = ({
  name,
  waitRender,
}) => {
  useEffect(() => {
    waitRender();
  }, []);
  return (
    <div>
      <img src={img} width={160} height={120} alt="" />
      {name}
    </div>
  );
};
const Item = HOC(Child);

const Index: React.FC<any> = () => {
  const list = [{ name: "图片1" }, { name: "图片2" }, { name: "图片3" }];
  return (
    <div>
      {list.map((item) => (
        <Item name={item.name} key={item.name} />
      ))}
    </div>
  );
};
export default Index;
